package com.jetpackframework.basemd;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.frameworkx.layout.activity_tab_view;
import com.google.android.material.tabs.TabLayout;
import com.jetpackframework.R2;
import com.jetpackframework.base.BaseActivity;
import com.jetpackframework.base.BaseFragment;

import java.util.List;

/**
 * TabLayout + ViewPager布局
 */
public abstract class BaseTabViewActivity extends BaseActivity<activity_tab_view> implements TabLayout.OnTabSelectedListener{
    @Override
    protected void initEventListener() {
        mBinding = getViewBind(R2.layout.activity_tab_view);
        setContentView(mBinding.getLayoutId());
        mBinding.bindView(getWindow().getDecorView());

        List<TabLayout.Tab> tabList = getTabList(mBinding.tab);
        for (TabLayout.Tab tab : tabList){
            mBinding.tab.addTab(tab);
        }
        mBinding.tab.addOnTabSelectedListener(this);
        mBinding.vp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
           @Override
           public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

           }

           @Override
           public void onPageSelected(int position) {
               mBinding.tab.selectTab(mBinding.tab.getTabAt(position));
           }

           @Override
           public void onPageScrollStateChanged(int state) {
           }
       });
       mBinding.vp.setAdapter(new FragmentStateAdapter(this) {
           @NonNull
           @Override
           public Fragment createFragment(int position) {
               return getFragmentByTab(tabList.get(position));
           }

           @Override
           public int getItemCount() {
               return tabList.size();
           }
       });
    }

    protected abstract BaseFragment getFragmentByTab(TabLayout.Tab tab);

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        mBinding.vp.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        mBinding.vp.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    /**
     * 返回所有的TAB
     * @return
     * @param tab
     */
    protected abstract List<TabLayout.Tab> getTabList(TabLayout tab);
}
